<template>
  <view class="page">
    <view class="navbar" :style="'background-image: url('+pageBg+');'">
      <u-navbar @leftClick="navLeftClick" :fixed="false" title="确认下单" placeholder bgColor="transparent"></u-navbar>
    </view>
    <view class="address">
      <view class="address-info" v-if="addressInfo.id" @click="jumpTo('/pages/myAddress/myAddress?type=1')">
        <view class="u-flex u-m-b-12">
          <view class="default" v-if="addressInfo.isDefault=='1'">默认</view>
          <view class="u-font-24" style="color: #818181;">{{ addressInfo.province }} {{ addressInfo.city }} {{ addressInfo.district }}</view>
        </view>
        <view class="u-flex u-row-between u-m-b-12">
          <view class="u-flex">
            <image class="u-m-r-16" style="width: 22rpx;height: 28rpx;" src="../../static/order/address.png" />
            <text class="u-font-28" style="color: #000000;font-weight: 600;">{{ addressInfo.adsDetail }}</text>
          </view>
          <u-icon color="#818181" size="24rpx" name="arrow-right"></u-icon>
        </view>
        <view class="u-flex">
          <view style="width: 38rpx;" />
          <view class="u-font-24" style="color: #333333;">{{ addressInfo.receiverName }} {{ addressInfo.receiverPhone }}</view>
        </view>
      </view>
      <view class="address-empty" v-else @click="jumpTo('/pages/myAddress/myAddress?type=1')">
        <view>
          <image style="width: 76rpx;height: 65.08rpx;" src="../../static/order/addressEmpty.png" />
        </view>
        <view class="u-flex"><text class="u-m-r-12">您尚未维护收货地址，请点击设置</text><u-icon color="#000000" size="24rpx" name="arrow-right"></u-icon></view>
      </view>
    </view>
    <view class="u-flex" style="padding-left: 18rpx;width: 702rpx;margin: 0 auto 10rpx;">
      <image class="u-m-r-10" style="width: 28rpx;height: 32.67rpx;" src="../../static/order/orderTitle.png" />
      <view class="u-font-28" style="color: #000000;">订单信息</view>
    </view>
    <view class="order-info">
      <view class="goods-list">
        <view class="goods-item" v-for="item in shopCarInfo.filterGoodsList" :key="item.id">
          <image class="goods-img" :src="item.subtitle?item.subtitle.split(',')[0]:''" mode="aspectFill" />
          <view class="u-flex-1">
            <view class="name u-line-2">{{ item.title }}</view>
            <view class="spec">{{ item.skuName }}</view>
            <view class="u-flex u-row-between u-col-bottom">
              <view class="price"><text>¥</text> {{ (item.priceCents/100).toFixed(2) }}</view>
              x {{ item.quantity }}
            </view>
          </view>
        </view>
      </view>
      <view class="u-flex u-row-between u-m-b-28 u-font-28">
        <view>商品总价</view>
        <view style="font-weight: 500;">¥ {{ shopCarInfo.totalAmount }}</view>
      </view>
      <view class="u-flex u-row-between u-m-b-28 u-font-28">
        <view>配送方式</view>
        <view>快递配送</view>
      </view>
      <view class="u-flex u-row-between u-m-b-28 u-font-28">
        <view class="u-flex">
          <text class="u-m-r-8">快递费用</text>
          <image style="width: 20rpx;height: 20rpx;" src="../../static/order/doubt.png" />
        </view>
        <view style="font-weight: 500;">¥ {{ shopCarInfo.freightAmount }}</view>
      </view>
      <view class="u-flex u-row-between u-m-b-30 u-font-28">
        <view>备注</view>
        <view style="width: 458rpx;">
          <u--input placeholder="（选）限20字" v-model="remark" border="none" :maxlength="20" :customStyle="{backgroundColor: '#F7F7F7',height: '70rpx'}"></u--input>
        </view>
      </view>
      <view class="u-m-b-26" style="width: 100%;height: 2rpx;background-color: #E1E1E1;"></view>
      <view class="u-text-right u-font-32" style="font-weight: 500;">订单总价：<text style="color: #E20300;">¥ {{ (+shopCarInfo.freightAmount + +shopCarInfo.totalAmount).toFixed(2) }}</text></view>
    </view>
    <view class="bottom" :style="isFullSucreen? 'padding-bottom: 30px;' : '' ">
      <view class="bottom-content">
        <view class="u-font-28" style="font-weight: 500;">订单总价：<text class="u-font-32" style="color: #E20300;">¥ {{ (+shopCarInfo.freightAmount + +shopCarInfo.totalAmount).toFixed(2) }}</text></view>
        <view class="btn" @click="generateOrder">立即支付</view>
      </view>
    </view>
    <payTypePopup :closePopup="() => showPayType=false" :showPayType="showPayType" :pay="pay" />
    <u-popup :show="showPayResult" :round="20" mode="center" closeable @close="showPayResult=false">
      <view class="pay-result customize-popup">
        <view class="popup-title u-m-b-40">支付结果</view>
        <view class="u-text-center u-font-28 u-m-b-52">支付过程中是否有遇到问题？</view>
        <view class="btn-list">
          <view class="btn-item" style="color: #56CB03;background-color: #fff;" @click="redirectTo('/pages/myOrder/myOrder?tabsCurrent=1')">取消支付</view>
          <view class="btn-item" style="color: #fff;background-color: #56CB03;" @click="redirectTo('/pages/confirmOrder/success')">我已完成支付</view>
        </view>
      </view>
		</u-popup>
  </view>
</template>

<script>
import payTypePopup from '../../components/payTypePopup.vue'
import pageBg from '../../static/order/confirmOrder.png'
import { getAddressesList, getOrderToken, submitOrder, aLiPay, wxPay, wxMiniAppPay } from '@/api/index'
import { isWeChatBrowser } from "@/common/util";

export default {
  components: {
    payTypePopup,
  },
  data() {
    return {
      pageBg,
      isFullSucreen: this.isFullSucreen,
      showPayType: false,
      showPayResult: false,
      shopCarInfo: {},
      addressInfo: {},
      remark: '',
      orderToken: '',
      userInfo: {},
    };
  },
  async onLoad() {
    this.userInfo = uni.getStorageSync('userInfo')
    uni.showLoading({ mask: true })
    await getOrderToken({}).then(res => {
      this.orderToken = res.data.orderToken
    })
    if(uni.getStorageSync('shopCarInfo')) {
      this.shopCarInfo = uni.getStorageSync('shopCarInfo')
      console.log(this.shopCarInfo);
      // uni.removeStorageSync('shopCarInfo')
    } else {
      this.jumoTab('/pages/gwc/gwc')
    }
    this.getAddresses()
  },
  onShow() {
    if(uni.getStorageSync('addressInfo')) {
      this.addressInfo = uni.getStorageSync('addressInfo')
      uni.removeStorageSync('addressInfo')
    }
  },
  methods: {
    getAddresses() {
      uni.showLoading({ mask: true })
      getAddressesList({pageNum: 100}).then(res => {
        uni.hideLoading()
        if(res.rows.length) {
          const index = res.rows.findIndex(v => v.isDefault == '1')
          if(index == -1) {
            this.addressInfo = res.rows[0]
          } else {
            this.addressInfo = res.rows[index]
          }
        } else {
          this.addressInfo = {}
        }
      })
    },
    pay(e) {
      const that = this
      this.showPayType = false
      if(e == 'ali') {
        const parameter = {
          totalAmount: (+this.shopCarInfo.freightAmount + +this.shopCarInfo.totalAmount).toFixed(2) * 1,
          payType: '2',
          outTradeNo: this.orderCode,
          subject: this.orderCode,
          deptId: uni.getStorageSync('userInfo').deptId,
        }
        const payUrl = `${window.location.origin}/pages/aliPay/aliPay?totalAmount=${parameter.totalAmount}&payType=${parameter.payType}&orderCode=${parameter.outTradeNo}&subject=${parameter.subject}&deptId=${parameter.deptId}&userId=${uni.getStorageSync('userInfo').userId}&userName=${uni.getStorageSync('userInfo').userName}&phonenumber=${uni.getStorageSync('userInfo').phonenumber}`
        uni.setClipboardData({
          data: payUrl,
          success: function () {
            uni.showModal({
              title: '提示',
              content: '复制成功,请使用系统浏览器支付.',
              showCancel: false,
              success: function (res) {
                that.showPayResult=true
              }
            });
          },
        });
        // aLiPay(parameter).then(res => {
        //   document.write(res.msg)
        // })
      } else if(e == 'wechat') {
        // 判断是否是微信浏览器
        if (isWeChatBrowser() && uni.getStorageSync('userInfo').openId) {
          uni.showLoading({ mask: true })
          wxMiniAppPay({ openId: uni.getStorageSync('userInfo').openId, payType: '2', orderCode: this.orderCode, totalAmount: ((+this.shopCarInfo.freightAmount + +this.shopCarInfo.totalAmount).toFixed(2) * 100).toFixed(0) * 1}).then((res) => {
            uni.hideLoading()
            const data = JSON.parse(res.data.payParams)
            const { appId, nonceStr, paySign, signType, timeStamp } = data
            let payParams = {
              appId: appId,
              timeStamp: timeStamp,
              nonceStr: nonceStr,
              package: data.package,
              signType: signType,
              paySign: paySign,
            }
            WeixinJSBridge.invoke('getBrandWCPayRequest', payParams, (res) => {
              this.showPayResult=true
              if (res.err_msg === 'get_brand_wcpay_request:ok') {
                uni.showToast({
                  icon: 'none',
                  title: `支付成功`
                })
              } else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
                uni.showToast({
                  icon: 'none',
                  title: `取消支付`
                })
              } else {
                uni.showToast({
                  icon: 'none',
                  title: `支付失败`
                })
              }
            })
          })
        } else {
          uni.showToast({
            icon: 'none',
            title: `h5支付暂未开通`
          })
        }

      } 
    },
    generateOrder() {
      if(!this.addressInfo.id) {
        uni.showToast({
          icon: 'none',
          title: `请选择收货地址`
        })
        return
      }
      const filList = ["吉林省", "黑龙江省", "辽宁省"]
      if(filList.some(v => v == this.addressInfo.province)) {
        uni.showToast({
          icon: 'none',
          title: `${filList.join(',')}暂不发货`
        })
        return
      }
      const parameter = {
        orderToken: this.orderToken,
        remark: this.remark,
        addressId: this.addressInfo.id,
        userRole: this.userInfo.postCode,
        payAmount: ((+this.shopCarInfo.freightAmount + +this.shopCarInfo.totalAmount).toFixed(2) * 100).toFixed(0) * 1
      }
      if(this.shopCarInfo.type == 'now') {
        parameter.quantity = this.shopCarInfo.quantity
        parameter.skuId = this.shopCarInfo.skuId
      }
      uni.showLoading({ mask: true })
      submitOrder(parameter).then(res => {
        uni.hideLoading()
        this.orderCode = res.data.order.orderCode
        this.showPayType=true
      }).catch(() => {
        this.goBack()
      })
    }
  },
};
</script>

<style lang="scss" scoped>
.page {
  width: 750rpx;
  min-height: 100vh;
  background-color: #F5F5F5;
  padding-bottom: 400rpx;
  position: relative;
  .navbar {
    background-repeat: no-repeat;
    background-size: 750rpx auto;
    margin-bottom: 12rpx;
  }
  .address {
    width: 702rpx;
    height: 168rpx;
    background: #FFFFFF;
    border-radius: 12rpx;
    margin: 0 auto 18rpx;
    .address-empty {
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      gap: 6rpx;
      font-size: 24rpx;
      color: #000000;
    }
    .address-info {
      width: 100%;
      height: 100%;
      padding: 18rpx;
      .default {
        width: 80rpx;
        height: 32rpx;
        border-radius: 200rpx;
        line-height: 32rpx;
        text-align: center;
        background: #FF6600;
        font-weight: 500;
        font-size: 20rpx;
        color: #FFFFFF;
        border-radius: 200rpx;
        margin-right: 16rpx;
      }
    }
  }
  .order-info {
    width: 702rpx;
    background: #FFFFFF;
    border-radius: 12rpx;
    padding: 20rpx 16rpx;
    margin: 0 auto;
    .goods-list {
      display: flex;
      flex-direction: column;
      gap: 20rpx;
      margin-bottom: 54rpx;
     .goods-item {
        display: flex;
        gap: 20rpx;
        position: relative;
        .goods-img {
          width: 180rpx;height: 180rpx;flex-shrink: 0;
        }
        .name {
          font-size: 28rpx;
          color: #000000;
          line-height: 44rpx;
          margin-bottom: 2rpx;
        }
        .spec {
          height: 44rpx;
          border-radius: 8rpx;
          font-size: 24rpx;
          color: #818181;
        }
        .price {
          font-weight: 500;
          font-size: 28rpx;
          color: #E20300;
          text {
            font-size: 24rpx;
          }
        }
      }
    }
  }
  .bottom {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    background: #FFFFFF;
    .bottom-content {
      width: 100%;
      background: #FFFFFF;
      padding: 12rpx 24rpx 12rpx 46rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .btn {
        width: 238rpx;
        height: 80rpx;
        line-height: 80rpx;
        text-align: center;
        background: #56CB03;
        border-radius: 200rpx;
        font-weight: 500;
        font-size: 28rpx;
        color: #FFFFFF;
      }
    }
  }
}

.pay-result {
  width: 632rpx;
  background-color: #fff;
  border-radius: 20rpx;
  padding-top: 60rpx;
  padding: 60rpx 24rpx 28rpx;
  
  .btn-list {
    display: flex;
    gap: 24rpx;
    .btn-item {
      flex: 1;
      height: 80rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border: 2rpx solid #56CB03;
      background-color: #FCDDBA;
      font-size: 28rpx;
      border-radius: 200rpx;
    }
  }
}
</style>
